class_name TargetDetector
extends Detector

@export var detect_radius:float = 30
@export_flags_2d_physics var obstacle_collsion_mask:int
@onready var ray_cast_2d: RayCast2D = $RayCast2D
var entities:Array = []
var visible_entities:Array = []
var camp_component:CampComponent

func init_detector(detect_component:DetectComponent):
	super.init_detector(detect_component)
	camp_component = detect_component.cur_entity.get_component_by_name("CampComponent") as CampComponent
	var data = detect_component.cur_entity.get_entity_data()
	obstacle_collsion_mask = data.get_obstacle_layer_mask()
	data.data_changed.connect(func(tag):
		if tag == "is_sky_entity":
			obstacle_collsion_mask = data.get_obstacle_layer_mask()
		)
func detect():
	super.detect()
	entities = GameCampSystem.get_target(camp_component.get_target_camps(),global_position,true,-1,detect_radius)
	visible_entities.clear()
	ray_cast_2d.collision_mask = obstacle_collsion_mask
	ray_cast_2d.enabled = true
	for entity in entities:
		ray_cast_2d.target_position = entity.global_position - global_position
		ray_cast_2d.force_raycast_update()
		if not ray_cast_2d.is_colliding():
			visible_entities.append(entity)
	ray_cast_2d.enabled = false
func get_closed_entity(target_type:GameEnum.TargetDetectorTargetType, pos:Vector2) -> Variant:
	match target_type:
		GameEnum.TargetDetectorTargetType.Target:
			var entities_copy = entities.duplicate()
			entities_copy.sort_custom(func (a:Vector2,b:Vector2):return (a-pos).length() < (b-pos).length())
			return entities_copy[0] if entities_copy.size()>0 else null
		GameEnum.TargetDetectorTargetType.VisibleTarget:
			var visible_entities_copy = visible_entities.duplicate()
			visible_entities_copy.sort_custom(func (a:Vector2,b:Vector2):return (a-pos).length() < (b-pos).length())
			return visible_entities_copy[0] if visible_entities_copy.size()>0 else null
		GameEnum.TargetDetectorTargetType.SameCampTarget:
			var camp_entities = GameCampSystem.get_target(camp_component.get_camp_camps(),global_position,true,-1,detect_radius)
			camp_entities.sort_custom(func (a:Vector2,b:Vector2):return (a-pos).length() < (b-pos).length())
			return camp_entities[0] if camp_entities.size()>0 else null
		_:
			return null
func _init() -> void:
	detector_type = GameEnum.DetectorType.Target
